#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "transfer_file.h"

const int MAX_NUM = 20;
const int MAX_LENGTH = 30;

static int index_of(const char ** lines ,int length ,const char * tarline);

int transfer_file(){
	char * src_file_path = "./data/string_line";
	char * dest_file_path = "./data/string_line_sorted";
	char data[MAX_NUM][MAX_LENGTH];
	const char * lines[MAX_NUM];
	FILE * src_file = fopen(src_file_path ,"r");
	FILE * dest_file = fopen(dest_file_path ,"w");
	if (!(src_file && dest_file)) {
		printf("open file error\n");
		return -1;
	}

	//读取，排序，写进lines
	char * line;
	int len = 0;
	for (; len<MAX_NUM; len++) {
		line = *(data + len);
		// line = data[len];
		if (!fgets(line ,MAX_LENGTH ,src_file)) break;
		int idx = index_of(lines ,len ,line);
		for (int j=len; j>idx; j--) {
			lines[j] = lines[j-1];
		}
		lines[idx] = line;
	}

	//写入目标文件
	for (int i=0; i<len; i++){
		fputs(lines[i] ,dest_file);
	}
	fclose(src_file);
	fclose(dest_file);
	printf("------------\n");
	printf("transfer file end..\n");

	return 0;
}


//查找一个字符串在已排序数组中的位置(相等值判断为小于)
//todo 用什么搜索算法
static int index_of(const char ** lines ,int length ,const char * tarline){
	const char * line;
	int i = 0;
	for (; i<length; i++) {
		line = lines[i];
		if (strcmp(line ,tarline) > 0) {
			break;
		}
	}
	return i;
}